import React from 'react';
import dva,{connect} from './dva'

function delay(ms){
  return new Promise((res)=>{
    setTimeout(() => {
      res()
    }, ms);
  })
}

const app = dva()
// debugger
app.model({
  namespace:'counter',//因为一个dvaapp中可以定义很多个模型
  state:{number:0}, //每个model里可以定义一个状态
  reducers:{
    add(state){
      return { number:state.number+1 }
    },
    asyncAdd(state){
      console.log('asyncAdd')
      return state
    }
  },
  effects:{
    // action=>store.dispatch(action)  effects=>redux-saga/effects
    // 核心原理：等待counter/asyncAdd派发后会执行次saga
    // 其实就是yield takeEvery(counter/asyncAdd,*asyncAdd)
    *asyncAdd(action,effects){
      let { call,put } = effects
      // yield call(delay,1000) //产出一个promise
      yield put({type:'add'}) //向仓库派发动作
    }
  }
})

function Counter(props){
  return (
    <div>
        <p>{props.number}</p>
        {/* 用时触发reducers和effects   */}
        <button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
    </div>
)
}

//store.getState() ={counter:{number:0}}
const ConnectedCounter = connect(state=>state.counter)(Counter)
// 指定要渲染的内容
app.router(()=><ConnectedCounter />)
// 开始渲染，原理就是 ReactDOM.render(()=><ConnectedCounter />,'#root')
app.start('#root')

